﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TinyUtil;

namespace MebAppInstaller
{
    class Program
    {
        /// <summary>
        /// 0 = appid
        /// 1 = appversion
        /// 2 = sessionid
        /// 3 = updateUrl
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(true);
                var appInfo = JsonFile.Read<AppInfo>("app.json");
                var dir = Environment.CurrentDirectory;
                var url = $"{args[3]}/api/app/getappfile?id={args[0]}&version={args[1]}&file={{0}}&hash={{1}}&sid={args[2]}";
                var updateForm = new DownloadForm(dir, url, appInfo.Files.ToArray());
                Application.Run(updateForm);
                if (updateForm.AllCompleted && updateForm.DialogResult == DialogResult.OK)
                {
                    var files = Directory.GetFiles(dir, "*.update");
                    foreach (var file in files)
                    {
                        var fileName = file.Replace(".update", "");
                        if (File.Exists(fileName))
                        {
                            File.Copy(file, fileName, true);
                            File.Delete(file);
                        }
                        else
                        {
                            File.Move(file, fileName);
                        }
                    }
                    PackUtil.PackApp(dir);
                }
                else
                {
                    var files = Directory.GetFiles(dir, "*.update");
                    foreach (var file in files)
                    {
                        File.Delete(file);
                    }
                    Environment.Exit(-1);
                }
            }
            catch (Exception ex)
            {

                var log = Path.Combine(Application.StartupPath, "install.log");
                File.WriteAllText(log, Assembly.GetExecutingAssembly().Location + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                try
                {
                    Process.Start(log);
                }
                catch { }
                throw;
            }
        }
    }
}
